﻿namespace LiSAClient.Core.Services.Factories
{
    using System;
    using System.Collections.Concurrent;

    public class ServiceFactory : IServiceFactory
    {
        private ServiceFactory()
        {
        }

        private static IServiceFactory instance;

        public static IServiceFactory Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ServiceFactory();
                }

                return instance;
            }
        }

        private ConcurrentDictionary<Type, object> instantiatedActioners;

        private ConcurrentDictionary<Type, object> InstantiatedActioners
        {
            get
            {
                if (this.instantiatedActioners == null)
                {
                    this.instantiatedActioners = new ConcurrentDictionary<Type, object>();
                }

                return this.instantiatedActioners;
            }
        }

        public T Get<T>() where T : BaseService, new()
        {
            if (this.InstantiatedActioners.ContainsKey(typeof(T)))
            {
                return this.InstantiatedActioners[typeof(T)] as T;
            }

            var ret = new T();

            this.InstantiatedActioners.GetOrAdd(typeof(T), ret);

            return ret;
        }
    }
}

